<template>
  <el-form
    label-width="60px"
    ref="formRef"
    :rules="accountRules"
    :model="account"
  >
    <el-form-item label="账号" prop="name">
      <el-input v-model="account.name" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="account.password" show-password />
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { computed, defineComponent, PropType, ref } from 'vue'
import { ElForm, ElMessage } from 'element-plus'

import { Account } from '../types'
import localCache from '@/utils/cache'
import { useStore } from '@/store/index'

export default defineComponent({
  props: {
    modelValue: {
      type: Object as PropType<Account>
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const store = useStore()

    const account = computed({
      get: () => props.modelValue,
      set: (newVal) => emit('update:modelValue', newVal)
    })

    const accountRules = {
      name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { pattern: /^[a-z0-9]{4,20}$/, message: '必须是6~20个字母或者数字',  trigger: 'blur' }
      ],
      password: [
        { required: true, message: '必须输入密码', trigger: 'blur' },
        { pattern: /^[a-z0-9]{3,}$/, message: '必须是3位以上数字', trigger: 'blur' }
      ]
    }

    const formRef = ref<InstanceType<typeof ElForm>>()

    const accountLoginAction = (isKeepPassword: boolean) => {
      formRef.value?.validate((isPassValidate) => {
        if (isPassValidate) {
          const name = account.value?.name
          const password = account.value?.password

          if (isKeepPassword) {
            localCache.setCache('name', name )
            localCache.setCache('password', password)
          } else {
            localCache.deleteCache('name')
            localCache.deleteCache('password')
          }
          // 登录
          store.dispatch('login/accountLoginAction',{ name, password })
        } else {
          ElMessage.error('账号或者密码错误~')
        }
      })
    }
    
    return {
      account,
      formRef,
      accountRules,
      accountLoginAction
    }
  }
})
</script>

<style scoped></style>
